package de.tum.in.eist.poll.client.views;

import java.util.ArrayList;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;

import de.tum.in.eist.poll.client.controllers.Controller;
import de.tum.in.eist.poll.client.views.widgets.questions.QuestionWidget;
import de.tum.in.eist.poll.shared.beans.Answer;
import de.tum.in.eist.poll.shared.beans.Feedback;
import de.tum.in.eist.poll.shared.beans.Notification;
import de.tum.in.eist.poll.shared.beans.Question;

/**
 * The Poll page
 * @author Sebastian Hofstetter
 * 
 */
public class PollView extends View {
	private VerticalPanel pollPanel = new VerticalPanel();

	private Button submitButton = new Button("Submit");

	private ArrayList<QuestionWidget> questionWidgets = new ArrayList<QuestionWidget>();

	public PollView() {
		Question[] questions = Controller.controller.getQuestions();

		// only if there are questions to answer, i.e. there is a lecture selected to which was not already feedback submitted
		if (questions != null && questions.length > 0 && !Controller.controller.isHasSubmitted()) {
			for (Question q : questions) {
				QuestionWidget w = q.getWidget();
				questionWidgets.add(w);
				pollPanel.add(w);
			}

			submitButton.addClickHandler(new ClickHandler() {
				
				@Override
				public void onClick(ClickEvent event) {

					Answer[] answers = new Answer[questionWidgets.size()];
					for (int i = 0; i < questionWidgets.size(); i++) {
						answers[i] = questionWidgets.get(i).getAnswer();
					}
					// send Feedback
					Controller.pollController.submitFeedback(new Feedback(Controller.controller.getLoggedInUser().getUserID(), Controller.controller.getCurrentLectureId(), answers));
					// notify clients
					Controller.controller.sendNotification(Notification.FeedbackSubmitted);
				}
			});
			pollPanel.add(submitButton);
		} else {
			// if there are no questions to show
			pollPanel.add(new Label("No Questions to answer. You probably have already submitted your answers."));
		}

		initWidget(pollPanel);
		pollPanel.addStyleName("pollView");
	}
}
